//
//  HelloWorldLayer.m
//  game1
//
//  Created by iD Student on 6/26/13.
//  Copyright iD Student 2013. All rights reserved.
//


// Import the interfaces
#import "HelloWorldLayer.h"

// Needed to obtain the Navigation Controller
#import "AppDelegate.h"

#pragma mark - HelloWorldLayer

#define playerleft (player.position.x - player.boundingBox.size.width/2)
#define playerright (player.position.x + player.boundingBox.size.width/2)
#define playertop (player.position.y + player.boundingBox.size.height/2)
#define playerbot (player.position.y - player.contentSize.height/2)
#define playercentx (player.position.x)
#define playercenty (player.position.y)

#define oneleft (ground[1].position.x - ground[1].boundingBox.size.width/2)
#define oneright (ground[1].position.x + ground[1].boundingBox.size.width/2)
#define onetop (ground[1].position.y + ground[1].boundingBox.size.height/2)
#define onebot (ground[1].position.y - ground[1].boundingBox.size.height/2)

#define twoleft (ground[2].position.x - ground[2].boundingBox.size.width/2)
#define tworight (ground[2].position.x + ground[2].boundingBox.size.width/2)
#define twotop (ground[2].position.y + ground[2].boundingBox.size.height/2)
#define twobot (ground[2].position.y - ground[2].boundingBox.size.height/2)


// HelloWorldLayer implementation
@implementation HelloWorldLayer
CCSprite *player;
CCSprite *ground[5];


// Helper class method that creates a Scene with the HelloWorldLayer as the only child.
+(CCScene *) scene
{
    // 'scene' is an autorelease object.
	CCScene *scene = [CCScene node];
	
	// 'layer' is an autorelease object.
	HelloWorldLayer *layer = [HelloWorldLayer node];
	
	// add layer as a child to scene
	[scene addChild: layer];
	
	// return the scene
	return scene;
}

float yvel = 4.5;

int playermovecounter = 0;

float grav;

float gravity;

float xvel = 2;
float xvelocity = 10;
float yvelocity = 0;

int score = 0;
int ulose = 0;

bool isTouchingGround;

int rightTileGIDBot;
int rightTileGIDTop;

CCLabelTTF *label;



// on "init" you need to initialize your instance
-(id) init
{
	// always call "super" init
	// Apple recommends to re-assign "self" with the "super's" return value
    if( (self=[super init]) ) {
        grav = 0.25;
        CGSize winSize = [CCDirector sharedDirector].winSize;
        
		player = [CCSprite spriteWithFile:@"player1.png"];
        
        [player setPosition:ccp(winSize.width * 0.1, winSize.height * 0.7)];
        
        tilemap = [CCTMXTiledMap tiledMapWithTMXFile:@"level1.tmx"];
        platformlayer = [tilemap layerNamed:@"Platforms"];
        winLayer = [tilemap layerNamed:@"Win Layer"];
        failLayer = [tilemap layerNamed:@"Fail Layer"];
        PickupSpeed = [tilemap layerNamed:@"PickupSpeed"];
        PickupFlight = [tilemap layerNamed:@"PickupFlight"];
        [tilemap setAnchorPoint:ccp(0,0)];
        
        animationFrames = [NSMutableArray arrayWithCapacity:2];
        animation = [CCAnimation animationWithSpriteFrames:animationFrames delay:.1];
        [animation addSpriteFrameWithFilename:@"player1.png"];
        [animation addSpriteFrameWithFilename:@"player2.png"];
        
        [player runAction:[CCRepeatForever actionWithAction:[CCAnimate actionWithAnimation:animation]]];
        
        [self addChild:player z:1];
        [self addChild:tilemap z:0];
        [self schedule:@selector(update:)]; // schedules the update function to run every frame
        [self schedule:@selector(collisionDetection:)];
        [self setTouchEnabled:TRUE];
        
	}
    
	return self;
}


-(CGPoint)tileCoordForPosition:(CGPoint) position{
    int x = floor(position.x / 32);
    int y = floor(((tilemap.mapSize.height * 32) - position.y)/32);
    
    return ccp(x,y);
}


-(void)update:(ccTime)delta{
    if(isTouchingGround){
        jumpcount = 0;
    }
    
    [tilemap setPosition:ccp(tilemap.position.x - xvelocity, tilemap.position.y)];
    [player setPosition:ccp(player.position.x, player.position.y + yvelocity)];
    
    if(rightTileGIDBot || rightTileGIDTop){
    }else{
        playermovecounter += xvelocity;
    }
    if (!isTouchingGround) {
        gravity = grav;
    }else {
        gravity = 0;
    }
    
    yvelocity -= gravity;
    
}
-(void)collisionDetection:(ccTime)delta{
    
    [self wallcollision];
}

-(void) wallcollision{
    //creates a coordinate
    CGPoint playerPositionBotleft = ccp(playerleft + playermovecounter, playerbot);
    CGPoint playerPositionBotright = ccp(playerright + playermovecounter, playerbot);
    CGPoint playerPositionTop = ccp(playerright + playermovecounter, playertop);
    CGPoint playerRightBot = ccp(playerright + playermovecounter, playercenty - 3);
    CGPoint playerRightTop = ccp(playerright + playermovecounter, playertop);
    
    CGPoint playerTilePosBotRight = [self tileCoordForPosition:playerPositionBotright];
    CGPoint playerTilePosBotLeft = [self tileCoordForPosition:playerPositionBotleft];
    CGPoint playerTilePosTop = [self tileCoordForPosition:playerPositionTop];
    CGPoint rightTilePosBot = [self tileCoordForPosition:playerRightBot];
    CGPoint rightTilePosTop = [self tileCoordForPosition:playerRightTop];
    //NSLog(@"(%f, %f)", playerTilePosBotRight.x, playerTilePosBotRight.y);
    
    int tileGIDBotLeft = [platformlayer tileGIDAt:playerTilePosBotLeft];
    int tileGIDBotRight = [platformlayer tileGIDAt:playerTilePosBotRight];
    int tileGIDTop = [platformlayer tileGIDAt:playerTilePosTop];
    rightTileGIDBot = [platformlayer tileGIDAt:rightTilePosBot];
    rightTileGIDTop = [platformlayer tileGIDAt:rightTilePosTop];
    int playerTileWin = [winLayer tileGIDAt:playerTilePosBotLeft];
    int playerTilefail = [failLayer tileGIDAt:playerTilePosBotLeft];
    int speedcatch = [PickupSpeed tileGIDAt:rightTilePosBot];
    int flightcatch = [PickupFlight tileGIDAt:rightTilePosBot];
    
    if(speedcatch){
        xvel = 4;
        
        CCSprite *tempSprite = [PickupFlight tileAt:rightTilePosBot];
        [tempSprite runAction:[CCCallFuncN actionWithTarget:self selector:@selector(removeSprite:)]];
        NSLog(@"run");
        [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(revertspeed) userInfo:nil repeats:NO];
    }
    if(flightcatch){
        grav = .02;
        //yvel = 2;
        
        CCSprite *tempSprite = [PickupFlight tileAt:rightTilePosBot];
        [tempSprite runAction:[CCCallFuncN actionWithTarget:self selector:@selector(removeSprite:)]];
        NSLog(@"fly");
        [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(revertgrav) userInfo:nil repeats:NO];
    }
    
    if(playerTileWin){
        xvelocity = 0;
        yvelocity = 0;
    }else if(playerTilefail){
        CGSize winSize = [CCDirector sharedDirector].winSize;
        
        [[CCDirector sharedDirector] replaceScene:[CCTransitionFade transitionWithDuration:0.0 scene:[HelloWorldLayer scene]]];
        playermovecounter = 0;
        [self revertspeed];
        [self revertgrav];
        
        [player setPosition:ccp(winSize.width * 0.1, winSize.height * 0.7)];
        
    }else{
        if (tileGIDBotRight){
            
            isTouchingGround = TRUE;
            CCSprite *tempTile1 = [platformlayer tileAt:playerTilePosBotRight];
            
            [player setPosition:ccp(player.position.x, tempTile1.position.y + tempTile1.contentSize.height + player.contentSize.height/2 + 1)];
            
        }else if (tileGIDBotLeft){
            
            isTouchingGround = TRUE;
            //yvelocity = 0;
            CCSprite *tempTile1 = [platformlayer tileAt:playerTilePosBotLeft];
            
            [player setPosition:ccp(player.position.x, tempTile1.position.y + tempTile1.contentSize.height + player.contentSize.height/2 + 1)];
            //yvelocity = 0;
            
        }else{
            isTouchingGround = FALSE;
        }
        
        if(tileGIDTop){
            if(yvelocity > 0){
                yvelocity = 0;
            }
        }
        
        if (rightTileGIDBot) {
            xvelocity = 0;
        }else{
            xvelocity = xvel;
        }
    }
    
}
-(void)removeSprite:(id)sender{
    CCSprite *sprite = (CCSprite *)sender;
    [sprite removeFromParentAndCleanup:YES];
    [self removeChild:[sprite parent] cleanup:true];
}

-(void) revertspeed{
    xvel = 2;
}
-(void) revertgrav{
    yvel = 4.5;
    grav = .25;
}

-(void) registerWithTouchDispatcher{
    [[[CCDirector sharedDirector]touchDispatcher]addTargetedDelegate:self priority:0 swallowsTouches:YES];
}

int jumpcount = 0;

-(BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event{
    //CGPoint touchLocation = [self convertTouchToNodeSpace:touch];
    if(jumpcount < 1){
        yvelocity = yvel;
        jumpcount ++;
    }
    
    
    
    return true;
}
// on "dealloc" you need to release all your retained objects
- (void) dealloc
{
	// in case you have something to dealloc, do it in this method
	// in this particular example nothing needs to be released.
	// cocos2d will automatically release all the children (Label)
	
	// don't forget to call "super dealloc"
	[super dealloc];
}

#pragma mark GameKit delegate


@end
